package com.zsc.shixun.exception;


import com.zsc.shixun.common.CommonResult;
import com.zsc.shixun.common.ResultUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * @author winner
 * @description: ZWYZY 定义的全局异常处理
 * @date 2020/4/14
 */
@Configuration
@RestControllerAdvice
public class ErrorExceptionHandler<T> {

    /**
     * api异常处理返回json封装字符串对象
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = ApiException.class)
    public CommonResult<Object> paramError(ApiException e) {
        return ResultUtil.error(e.getCode(), e.getMessage(), e.getData());
    }


    /**
     * 校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public CommonResult bindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
        return ResultUtil.error(400, message);
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public CommonResult methodArgumentTypeMismatchExceptionHandler(MethodArgumentTypeMismatchException e) {
//        String message = e.getLocalizedMessage().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return ResultUtil.error(400, "数据验证错误");
    }


    /**
     * 校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public CommonResult constraintViolationExceptionHandler(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return ResultUtil.error(400, message);
    }


    /**
     * 校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public CommonResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return ResultUtil.error(400, message);
    }
}
